<template>
  <van-popup
    v-model="show"
    position="bottom">
    <div class="wd-input-dropdown">
      <div class="van-hairline--top-bottom van-picker__toolbar">
        <button @click="mCancel" class="van-picker__cancel">取消</button>
        <button @click="mConfirm" class="van-picker__confirm">确认</button>
      </div>
      <van-field ref="searchElem" v-model="searchVal" :placeholder="placeholder">
        <van-button :loading="loading" @click="mSearch" slot="button" size="small" type="primary">查询</van-button>
      </van-field>
      <van-cell :center="true" v-if="dropdownList.length < 1">
        <p class="wd-input-dropdown__null">{{loading ? '加载中...' : '无数据'}}</p>
      </van-cell>
      <div v-else class="wd-input-dropdown__list">
        <van-cell-group>
          <van-cell
            v-for="item in dropdownList"
            clickable
            @click="selected = item"
            :title="item.label"
            :class="{checked: item === selected}">
            <i v-if="item === selected" class="van-icon van-icon-success"></i>
          </van-cell>
        </van-cell-group>
      </div>
    </div>
  </van-popup>
</template>

<script>
  export default {
    props: {
      placeholder: '',
      visible: false
    },
    data() {
      return {
        show: false,
        selected: null,
        searchVal: '',
        dropdownList: [],
        loading: false
      }
    },
    watch: {
      visible(n) {
        this.show = n
        if (n) {
          this.$emit('search', '')
        }
      },
      show(n) {
        // if (n) {
        //   setTimeout(() => {
        //     this.$refs.searchElem.focus()
        //   }, 50)
        // }
        this.$emit('update:visible', n)
      }
    },
    methods: {
      mSearch() {
        this.dropdownList = []
        if (this.searchVal.trim() === '') return
        this.$emit('search', this.searchVal)
      },
      mCancel() {
        this.show = false
        this.selected = null
        this.dropdownList = []
        this.searchVal = ''
      },
      mConfirm() {
        if (!this.selected) {
          this.$toast('你没有选择任何信息！')
        } else {
          this.$emit('confirm', this.selected)
          this.selected = null
          this.dropdownList = []
          this.searchVal = ''
        }
      }
    }
  }
</script>